package com.chang.bootplus.config.security;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;

import com.chang.bootplus.base.constant.Constant;
import com.chang.bootplus.base.utils.RedisUtil;
import com.chang.bootplus.config.exception.CaptchaException;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.apache.http.protocol.HTTP;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

@Component
public class CaptchaFilter extends OncePerRequestFilter {

	@Autowired
	RedisUtil redisUtil;



	HttpServletRequest httpServletRequest1;


	@Autowired
	LoginFailureHandler loginFailureHandler;

	@Override
	protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
		httpServletRequest1=httpServletRequest;
		String url = httpServletRequest.getRequestURI();

		if ("/login".equals(url) && httpServletRequest.getMethod().equals("POST")) {
			try{
				// 校验验证码
				validate(httpServletRequest);
			} catch (CaptchaException e) {
				// 交给认证失败处理器
			 	loginFailureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, e);
			}
		}
		filterChain.doFilter(httpServletRequest1, httpServletResponse);
	}
	// 校验验证码逻辑
	private void validate(HttpServletRequest request) throws IOException {
		ObjectMapper mapper = new ObjectMapper();
		Map<String,String> map=null;
		if (request.getContentType().equals(MediaType.APPLICATION_JSON_UTF8_VALUE) || request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE)) {
			httpServletRequest1=new BodyReaderHttpServletRequestWrapper(httpServletRequest1);
			try (BufferedReader reader = new BodyReaderHttpServletRequestWrapper(httpServletRequest1).getReader()) {
				map = mapper.readValue(reader, Map.class);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		String code=map.get("code");
		String key=map.get("captchakey");
		if (StringUtils.isBlank(code) || StringUtils.isBlank(key)) {
			throw new CaptchaException("验证码错误");
		}

		System.out.println(redisUtil.hget(Constant.CAPTCHA_KEY, key));
		if (!code.equals(redisUtil.hget(Constant.CAPTCHA_KEY, key))) {
			System.out.println("验证码错误");
			throw new CaptchaException("验证码错误");
		}
		// 一次性使用
		redisUtil.hdel(Constant.CAPTCHA_KEY, key);
	}

}
